package com.douxg.fastCoding.web.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.douxg.fastCoding.db.*;
import com.douxg.fastCoding.spring.consts.BizCode;
import com.douxg.fastCoding.spring.exception.BizRuntimeException;
import com.douxg.fastCoding.web.consts.FunctionEnum;
import com.douxg.fastCoding.web.dto.CodeGenerateDto;
import com.douxg.fastCoding.web.dto.DbInfoDto;
import com.douxg.fastCoding.web.dto.EnjoyDto;
import com.douxg.fastCoding.web.eo.DbInfoEo;
import com.douxg.fastCoding.web.vo.DbInfoVo;
import com.jfinal.kit.Kv;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Auther douxg
 * @Date 2020/7/31 10:18
 */
@Service
public class CodeService {
    @Resource
    private EnjoyService enjoyService;
    @Resource
    private DbInfoService dbInfoService;

    public String generate(CodeGenerateDto dto) {
        checkDto(dto);
        DbInfoDto dbInfoDto = new DbInfoDto();
        dbInfoDto.setName(dto.getDbAlias());
        DbInfoVo dbInfoVo = dbInfoService.queryOne(dbInfoDto);
        if (dbInfoVo == null) {
            throw new BizRuntimeException(BizCode.DB_NO_DATA);
        }
        DbInfoEo dbInfoEo = BeanUtil.copyProperties(dbInfoVo, DbInfoEo.class);
        DbFunction dbFunction = DbFactory.getDbFunction(dbInfoEo.getDbType());
        String tableName = dto.getTableName();
        List<ColumnsEO> columnsEos = dbFunction.getColumnsEo(dbInfoEo, tableName);
        ConfigEO configEO = ConfigManager.getConfig(dbInfoEo, columnsEos);
        configEO.setTableName(tableName);
        Kv kv = Kv.by("columns", columnsEos).set("config", configEO);
        EnjoyDto enjoyDto = new EnjoyDto();
        enjoyDto.setName(dto.getEnjoyName());
        enjoyDto.setGroupName(dto.getGroupName());
        enjoyDto.setFunctionName(FunctionEnum.CODE.getName());
        String entity = enjoyService.run(enjoyDto, null, kv);
        return entity;
    }

    private void checkDto(CodeGenerateDto dto) {
        isBlank(dto.getDbAlias());
        isBlank(dto.getEnjoyName());
        isBlank(dto.getGroupName());
        isBlank(dto.getTableName());
    }

    private void isBlank(String value) {
        if (StrUtil.isBlank(value)) {
            throw new BizRuntimeException(BizCode.PARAM_ISNULL);
        }
    }

    public static void main(String[] args) {
        Integer a=4;
        Integer b=new Integer(4);
        System.out.println(b==4);
    }
}
